const app = getApp();
var config = app.globalData.config;
const http = require('../../utils/http.js');
const jhmd5 = require('../../utils/md5.js');
const jhpay = require('../../utils/pay.js');
Page({

	/**
	 * 页面的初始数据
	 */
	data: {
		mode: '', // add,edit 添加或者编辑
		student_list_active_id: '', //选中的学生id
		student_active_index: '', //选择的学生列表下标
		student_list: [
			
		],
		sex_list: [{
				id: 1,
				sex_name: '男'
			},
			{
				id: 2,
				sex_name: '女'
			}
		],
		school_list: [],
		parentage_list:[{
					id: 0,
					parentage_name: '爸爸'
				},
				{
					id: 1,
					parentage_name: '妈妈'
				}
		],//亲子关系
		grade_list: [{
				id: 3,
				grade_name: '一年级'
			},
			{
				id: 4,
				grade_name: '二年级'
			},
			{
				id: 5,
				grade_name: '三年级'
			}
		],
		class_list: [{
				id: 6,
				class_name: '一班'
			},
			{
				id: 7,
				class_name: '二班'
			}
		],
		add_item: {
			parentage_index:'',
			student_name: '',
			sex_index: '',
			birthday: '',
			school_index: '',
			grade_index: '',
			class_index: ''
		},
		edit_item: {},
		schoolIdDauflt: 0,
		initFlag : false,//初始化参数
		isShow:false	,//模态框参数
		sname:'xxx'	,//模态框参数-选中学生姓名
		order_num:"",//订单编号
		bank_mac:"",//银行mac
		no_multipleclick:false,//防止多次点击提交订单
    no_addstudent:false,//防止多次点击新增学生
    mealsName:[],
    mealsData:[],
    period_id:'0',
    cycle_id:'0',
    money:'',
    meals_id:1,
	},
	onReady: function() {
		if (!app.login()) {
			return;
		}
	},
	onLoad(options) {
		var that = this;
		this.classId = options.id; //前面传的 班级id【课程id】
		this.cname = options.cname;
		this.tuition = options.tuition;
		this.setData({
			'cname': that.cname,
			'tuition': that.tuition
		})
		
		this.getSchoolList(); //选项框-获取学校-班级
		this.getGradeList(); //选项框-获取年级
		this.getStudentList(); //学生列表初始化
		
    this.getParentageList();	//获取【亲子关系】
    this.getMealsData();  //获取餐费信息
  },

  //获取餐费信息
  getMealsData(){
    let that=this
    let _mealsData=[]
    let _meals_id=''
    let _money=''
    http.httpPost(config.getMealsData, {}, function(e) {
      for(let i=0;i<e.data.mealsData.length;i++){
        if(e.data.mealsName[that.data.period_id]==e.data.mealsData[i].name){
          _mealsData.push(e.data.mealsData[i])
          _meals_id=_mealsData[0].id
          _money=_mealsData[0].money
        }
      }
      that.setData({
        mealsName:e.data.mealsName,
        mealsData:_mealsData,
        meals_id:_meals_id,
        money:_money
      })
    })
  },

  //选择时段
  choosedPeriod(e){
    this.setData({
      mealsData:[],
      period_id:e.currentTarget.dataset.id,
    })
    this.getMealsData()
  },
  //选择周期
  choosedCycle(e){
    this.setData({
      meals_id:e.currentTarget.dataset.id,
      money:e.currentTarget.dataset.money
    })
  },
	getStudentList() { //获取学生列表
		var that = this;
		http.httpPost(config.get_student_list, {}, function(e) {
			that.student_list = e.data;
			console.log(that.student_list )
			if(that.data.initFlag==false && e.data.length>0){
				that.data.initFlag = true;
				that.data.student_list_active_id = e.data[0].id;	//默认选择第一个孩子
				that.data.student_active_index = 0;
			
				that.setData({
					'student_list': e.data,
					'initFlag': true,
					'student_list_active_id': e.data[0].id,
					'student_active_index': 0,
					'mode': 'edit',
					'edit_item': e.data[0]
				})
			}
			
			
		});
	},
	getParentageList(){//获取亲子关系
		var that = this;
		http.httpPost(config.get_parentage_list, {}, function(e) {
			that.parentage_list = e.data;
			
			that.setData({
				'parentage_list': e.data
			})
			
		});
	},
	//更改亲子关系
	parentageChange: function(e) {
		let add_item = this.data.add_item;
		add_item.parentage_index = e.detail.value;
		this.setData({
			add_item: add_item
		})
	},
	//更改学生姓名
	studentnameChange: function(e) {
		let add_item = this.data.add_item;
		add_item.student_name = e.detail.value;
		this.setData({
			add_item: add_item
		})
	},
	//更改学生性别
	sexChange: function(e) {
		let add_item = this.data.add_item;
		add_item.sex_index = e.detail.value;
		this.setData({
			add_item: add_item
		})
	},
	//更改出生日期
	birthdayChange: function(e) {
		let add_item = this.data.add_item;
		add_item.birthday = e.detail.value;
		this.setData({
			add_item: add_item
		})
	},
	//更改学校
	schoolChange: function(e) {
		let add_item = this.data.add_item;
		add_item.school_index = e.detail.value;
		this.setData({
			add_item: add_item
		})

		//改变班级列表
		this.schoolIdDauflt = this.school_list[e.detail.value].id;
		this.getClassList(this.schoolIdDauflt);
		
		//清空年级、班级
		add_item.grade_index = '';
		add_item.class_index = '';
		this.setData({
			add_item: add_item
		});
	},
	getSchoolList() { //获取【校园列表】
		var that = this;
		http.httpPost(config.get_school_list, {
			showStatus: true
		}, function(e) {
			that.school_list = e.data;
			that.setData({
				'school_list': e.data
			})
			//
			if (e.data.length > 0) {
				that.schoolIdDauflt = e.data[0].id;
				that.setData({
					schoolIdDauflt: e.data[0].id
				})
				var school_id = e.data[0].id;
				that.getClassList(school_id)
			}

		});

	},
	getClassList(school_id =null,grade_id = null) { //获取【报名课程】
		var that = this;
		http.httpPost(config.get_studentclasses_list, {
			school_id: school_id,
			grade_id:grade_id
		}, function(e) {
			that.class_list = e.data;

			that.setData({
				'class_list': e.data
			})
		});
	},
	//更改年级
	gradeChange: function(e) {
		let add_item = this.data.add_item;
		add_item.grade_index = e.detail.value;
		this.setData({
			add_item: add_item
		});
		
		let grade_id = this.data.grade_list[e.detail.value].id;
		this.getClassList(this.schoolIdDauflt,grade_id);
		
		//清空班级选择
		add_item.class_index = '';
		this.setData({
			add_item: add_item
		});
	},
	getGradeList() { //获取【年级】
		var that = this;
		http.httpPost(config.get_grade_list, {
			showStatus: true
		}, function(e) {
			that.grade_list = e.data;

			that.setData({
				'grade_list': e.data
			})

		});
	},
	//更改班级
	classChange: function(e) {
		let add_item = this.data.add_item;
		add_item.class_index = e.detail.value;
		this.setData({
			add_item: add_item
		})

	},

	//添加学生
	addStudent: function(e) {
		if(!this.data.no_addstudent){
			this.data.no_addstudent = true;
			this.setData({
				no_addstudent: true
			})
		}else{
			wx.showToast({
				title: "添加学生中，请稍后再试",
				icon: 'none',
				duration: 1000,
				mask: true
			});
		}
		
		let add_item = {};
		if (this.data.add_item.parentage_index == '') {
			wx.showToast({
				title: '请选择亲子关系',
				icon: 'none',
				duration: 1000,
				mask: true
			});
			return;
		}
		add_item.parentage_name = this.data.parentage_list[this.data.add_item.parentage_index].parentage_name;
		
		if (this.data.add_item.student_name == '') {
			wx.showToast({
				title: '请输入学生姓名',
				icon: 'none',
				duration: 1000,
				mask: true
			});
			return;
		}
		add_item.student_name = this.data.add_item.student_name;

		if (this.data.add_item.sex_index == '') {
			wx.showToast({
				title: '请选择学生性别',
				icon: 'none',
				duration: 1000,
				mask: true
			});
			return;
		}
		add_item.sex = this.data.sex_list[this.data.add_item.sex_index].id;

		if (this.data.add_item.birthday == '') {
			wx.showToast({
				title: '请选择出生日期',
				icon: 'none',
				duration: 1000,
				mask: true
			});
			return;
		}
		add_item.birthday = this.data.add_item.birthday;

		if (this.data.add_item.school_index == '') {
			wx.showToast({
				title: '请选择学校',
				icon: 'none',
				duration: 1000,
				mask: true
			});
			return;
		}
		add_item.school_id = this.data.school_list[this.data.add_item.school_index].id;
		add_item.school_name = this.data.school_list[this.data.add_item.school_index].name;

		if (this.data.add_item.grade_index == '') {
			wx.showToast({
				title: '请选择年级',
				icon: 'none',
				duration: 1000,
				mask: true
			});
			return;
		}
		add_item.grade_id = this.data.grade_list[this.data.add_item.grade_index].id;
		add_item.grade_name = this.data.grade_list[this.data.add_item.grade_index].grade_name;

		if (this.data.add_item.class_index == '') {
			wx.showToast({
				title: '请选择班级',
				icon: 'none',
				duration: 1000,
				mask: true
			});
			return;
		}
		add_item.class_id = this.data.class_list[this.data.add_item.class_index].id;
		add_item.class_name = this.data.class_list[this.data.add_item.class_index].class_name;

		let student_list = this.data.student_list;
		// student_list.push(add_item);

		//添加孩子信息
		var that = this;
		http.httpPost(config.get_add_childdata, {
			parentage:that.data.add_item.parentage_index,
			studentname: that.data.add_item.student_name,
			school_id: that.data.school_list[that.data.add_item.school_index].id,
			sex: that.data.sex_list[that.data.add_item.sex_index].id,
			birthtime: that.data.add_item.birthday,
			grade_id: that.data.grade_list[that.data.add_item.grade_index].id,
			class_id: that.data.class_list[that.data.add_item.class_index].id,
		}, function(e) {
			wx.showToast({
				title: e.msg,
				icon: 'none',
				duration: 1000,
				mask: true
			});
			if (e.code == 1) {
				add_item.id = e.data;
				student_list.push(add_item);
			}
			that.setData({
				'student_list': student_list,
				'add_item': {
					parentage_index:'',
					student_name: '',
					sex_index: '',
					birthday: '',
					school_index: '',
					grade_index: '',
					class_index: ''
				}
			})
		});

	},
	//激活报名学生
	selectStudent: function(e) {
		console.log(this.data.student_list);
		this.data.student_list_active_id = e.currentTarget.dataset.id;
		this.data.student_active_index = e.currentTarget.dataset.key;
		this.setData({
			"student_list_active_id": e.currentTarget.dataset.id,
			"student_active_index": e.currentTarget.dataset.key,
			mode: 'edit',
			edit_item: this.data.student_list[e.currentTarget.dataset.key]
		})
	},
	//进入添加模式
	studentModeAdd: function(e) {
		this.setData({
			mode: 'add'
		})
	},
	//删除学生
	delete_item: function(e) {
		var that = this;
		let student_list = this.data.student_list;
		student_list.forEach(function(item, index) {
			if (item.id == that.data.edit_item.id) {
				http.httpPost(config.del_student, {
					student_id: item.id
				}, function(e) {
					student_list.splice(index, 1);
					wx.showToast({
						title: '删除成功',
						icon: 'none',
						duration: 1000,
						mask: true
					})
					that.setData({
						student_list: student_list,
						mode: ''
					})

				});

				return;
			}
		});
	},
	isWxPayBtn(){
		if (this.data.student_list_active_id == undefined) {
			wx.showToast({
				title: '请选择学生',
				icon: 'none',
				duration: 1000,
				mask: true
			})
			return;
		} else {
			var _isPay = false;
			this.isShow = true;
			this.sname = this.student_list[this.data.student_active_index].student_name;
			this.setData({
				isShow: true,
				sname:this.sname
			})
		
		}
	},
	cancelBtn(){//模态框-取消
		this.isShow = false;
		this.setData({
			isShow: false,
			no_multipleclick: false
		})
	},
	confirmPayBtn(){//模态框-确认支付
		//防止多次点击
		if(this.data.no_multipleclick){
			wx.showToast({
				title: '请勿多次点击确认',
				icon: 'none',
				duration: 1000,
				mask: true
			});
			return;
		}else{
			this.data.no_multipleclick = true;
			this.setData({
				no_multipleclick: true
			});
		}
	
		this.goEnroll();
		// this.wxPayBtn();
	},

	//提交报名
	goEnroll(){	
		var that = this;
		var _student_id = this.data.student_list_active_id;
		var _list_index = this.data.student_active_index;
		var _meals_id = this.data.meals_id;	//fixme
    
		http.httpPost(config.add_meals_enroll, {
			student_id: _student_id,
			meals_id: _meals_id,
		}, function(e) {
			that.buildBankParam(e.data.order_num,e.data.money);
		});
				
	},


  buildBankParam(order_num,total_money){//构建参数
    var that = this;
    var user_openid = app.globalData.userInfo.openid;
    var bankUrl = "";
    
    var _timeStamp = "";
    var _nonceStr = "";
    var _package = "";
    var _signType = "";
    var _paySign = "";
    // console.log("order_num:"+order_num);
    //测试fixme 0.01是金额；倒数第二个是时间
    var bank_str = jhpay.make(order_num,total_money,"","","","","","",user_openid);

    // var _str = "MERCHANTID=105000582994528&POSID=070424517&BRANCHID=350000000&ORDERID=kc202209011147059891&PAYMENT=0.01&CURCODE=01&TXCODE=530590&REMARK1=&REMARK2=&TYPE=1&PUB=65ad01f50fddeaeaf3d7a35d020111&GATEWAY=0&CLIENTIP=120.78.216.181&REGINFO=&PROINFO=&REFERER=&TRADE_TYPE=MINIPRO&SUB_APPID=wx64c7003a659575d7&SUB_OPENID=ofXpS490isnG7fCuIlM3Hit14A_s";
    var bank_mac = jhmd5.hex_md5(bank_str);
    // console.log(bank_mac);
    
    var bankUrl = "https://ibsbjstar.ccb.com.cn/CCBIS/ccbMain?CCB_IBSVersion=V6"+"&"+bank_str+"&MAC="+bank_mac;

    //调用银行接口 todo
    http.httpGet(bankUrl,{},function(e){
      
      var resStatus = e.SUCCESS;
      if(resStatus=="true"){
        var PAYURL = e.PAYURL;
        http.httpGet(PAYURL,{},function(e){
          
          if(e.SUCCESS=="true"){
            _timeStamp = e.timeStamp;
            _nonceStr = e.nonceStr;
            _package = e.package;
            _signType = e.signType;
            _paySign = e.paySign;
            
            that.wxPayBtn(order_num,bank_str,bank_mac,_timeStamp,_nonceStr,_package,_signType,_paySign);
            
          }else{
            wx.showToast({
              title: "支付失败，请稍后再试",
              icon: 'none',
              duration: 1000,
              mask: true
            });
          }
        })
      }
      
    })
      
    
  },

  wxPayBtn(order_num,bank_str,bank_mac,_timeStamp,_nonceStr,_package,_signType,_paySign) { //微信支付
    var that = this;
    wx.requestPayment({
      timeStamp: _timeStamp,
       nonceStr: _nonceStr,
       package: _package,
       signType: _signType,
       paySign: _paySign,
      success: res => {
        setTimeout(function() {
          wx.redirectTo({
            url: '../../pages/index/index'
          })
        }, 200);
      },
      fail: res => {
        that.setData({
          button_status : true
        })
      }
    })
  },

})
